package com.qiantu.phone.ui.fragment.device;

import android.view.View;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.entity.ControlDataFloorHeatingBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.FloorHeatingDeviceModeValueAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.FloorHeatingSeekBar;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * desc   : 地暖设备
 */
public final class FloorHeatingFragment extends BaseDeviceFragment {

    private FloorHeatingSeekBar floorHeatingSeekBar;
    private TextView tvModeLabel;
    private RecyclerView modeValueRecyclerView;
    private FloorHeatingDeviceModeValueAdapter mFloorHeatingDeviceModeValueAdapter;
    private ControlDataFloorHeatingBean floorHeatingInfoBean;
    private ControlDataFloorHeatingBean.ControlData controlData;

    public static FloorHeatingFragment newInstance() {
        FloorHeatingFragment fragment = new FloorHeatingFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_floor_heating;
    }

    @Override
    protected void initView() {
        super.initView();
        floorHeatingSeekBar = findViewById(R.id.floor_heating_seek_bar);
        tvModeLabel = findViewById(R.id.tv_mode_label);
        modeValueRecyclerView = findViewById(R.id.mode_value_recycler_view);
        floorHeatingSeekBar.setOnChangeListener(new FloorHeatingSeekBar.OnChangeListener() {

            @Override
            public void onValueChanged(float value) {

            }

            @Override
            public void onStopTrackingTouch(float value) {
                DeviceState deviceState = mDevice.getStateData();
                Integer temperature = deviceState.getStatus().getTemperature();
                if (Float.valueOf(temperature) != value) {
                    temperatureOperation((int)value);
                }
            }

            @Override
            public void onSwitch(boolean isOpen) {
//                setStatusBySwitch(isOpen);
                floorHeatingSeekBar.setOpenState(!isOpen);
                switchOperation();
            }
        });
        floorHeatingInfoBean = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataFloorHeatingBean.class);
        controlData = floorHeatingInfoBean.getControlData();
        floorHeatingSeekBar.setMinMax(controlData.getTemperature_min(), controlData.getTemperature_max());
//        if(controlData.getMode() != null && controlData.getMode().size() > 0){
//            mFloorHeatingDeviceModeValueAdapter = new FloorHeatingDeviceModeValueAdapter(getContext());
//            mFloorHeatingDeviceModeValueAdapter.setData(controlData.getMode());
//            mFloorHeatingDeviceModeValueAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
//                    if(!floorHeatingSeekBar.isOpen()){
//                        ToastUtils.show(R.string.device_off_disable);
//                        return;
//                    }
//                    mFloorHeatingDeviceModeValueAdapter.selectItem(position);
//                    DeviceModeValue valueBean = mFloorHeatingDeviceModeValueAdapter.getData().get(position);
//                    modeOperation(valueBean.getValue());
//                }
//            });
//            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
//            linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
//            modeValueRecyclerView.setLayoutManager(linearLayoutManager);
//            modeValueRecyclerView.setAdapter(mFloorHeatingDeviceModeValueAdapter);
            updateView();
//        }else{
            tvModeLabel.setVisibility(View.GONE);
            modeValueRecyclerView.setVisibility(View.GONE);
//        }
    }

    private void switchOperation() {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, floorHeatingSeekBar.isOpen() ? 0 : 1);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setIsOpen(!floorHeatingSeekBar.isOpen());
                floorHeatingSeekBar.setOpenState(mDevice.getIsOpen());
                setStatusBySwitch(mDevice.getIsOpen());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void temperatureOperation(int temperature) {
        if(!mDevice.getIsOpen()){
            ToastUtils.show(R.string.device_off_disable);
            return;
        }
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.TEMPERATURE, temperature);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setTemperature(temperature);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void modeOperation(int mode) {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.MODE, mode);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setMode(mode);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void selectValue(Integer value){
        //设备关闭不设置设置缓存里的模式
        if(!floorHeatingSeekBar.isOpen() || mFloorHeatingDeviceModeValueAdapter == null || mFloorHeatingDeviceModeValueAdapter.getData() == null){
            return;
        }
        for(int i=0; i<mFloorHeatingDeviceModeValueAdapter.getData().size(); i++){
            if(mFloorHeatingDeviceModeValueAdapter.getData().get(i).getValue() == value){
                mFloorHeatingDeviceModeValueAdapter.selectItem(i);
                break;
            }
        }
    }

    private void setStatusBySwitch(boolean isOpen){
        floorHeatingSeekBar.setOpenState(isOpen);
        if(mFloorHeatingDeviceModeValueAdapter == null || mFloorHeatingDeviceModeValueAdapter.getData() == null){
            return;
        }
        if(isOpen){
            selectValue(mDevice.getMode());
        }else{
            mFloorHeatingDeviceModeValueAdapter.clearSelected();
        }
    }

    protected void updateView() {
        super.updateView();
//        if (mDevice.isIsOnline()) {
            floorHeatingSeekBar.setEnabled(true);
            floorHeatingSeekBar.setTemp(Float.valueOf(mDevice.getTemperature()));
            setStatusBySwitch(mDevice.getIsOpen());
//        } else {
//            floorHeatingSeekBar.setEnabled(false);
//            setStatusBySwitch(false);
//        }
    }
}